package com.sc.common.shiro.realm;

import com.sc.common.pojo.Teacher;
import com.sc.common.service.TeacherService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class TeacherRealm extends AuthorizingRealm {
    @Autowired
    TeacherService ts;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String username = (String) token.getPrincipal();

        //通过用户名获取用户
        Teacher teacher = ts.selectByUsername(username);
        //判断是否存在，不存在则抛出异常UnknownAccountException异常
        if (teacher == null)
            throw new UnknownAccountException();
        //判断是否启用，冻结状态抛出异常
        if (!teacher.getStatus().equals(1))
            throw new LockedAccountException();
        //存在则存入SimpleAuthenticationInfo中
        //需要传入四个参数：1、登录的对象 2、登录的密码  3、盐值 4、Realm名称
        Object password = teacher.getPassword();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                teacher,
                password,
                new SimpleByteSource(teacher.getUsername()),
                getName()

        );
        return info;
    }
}
